<script setup lang="ts">
import {ref, useTemplateRef} from 'vue';
import CrudForm from './CrudForm.vue';
import type { FormConfig } from '@/components/crud/types';
import { getEntry, StrapiResponse, updateEntry} from "@/api/strapi";
import {ErrorUtils} from "@/utils/ErrorUtils";
const isOpen = ref(false);
const isLoading = ref(false);
defineOptions({
  name: "UpdateDialog",
})
// 定义 props，接收弹窗标题、是否显示弹窗、表单配置、初始数据和 modelValue
const props = defineProps<{
  title: string;
  url: string;
  config: FormConfig[];
}>();
const form = ref<Record<string, any>>({});
const id = ref<string | number>();
const crudForm = useTemplateRef<typeof CrudForm>('crudForm')
// 定义 emit 事件，用于关闭弹窗、提交表单和更新 modelValue
const emit = defineEmits(['success', 'close']);

// 关闭弹窗的方法
const handleClose = () => {
  emit('close');
};
// 提交表单的方法
const save = () => {
  if (!id.value) {
    return ErrorUtils.handleError(new Error("id is required"));
  }
  isLoading.value = true;
  // 提交后关闭弹窗
  crudForm.value?.validate()
      .then(() => updateEntry(props.url, id.value || '', form.value))
      .then((res: any) => {
        emit('success', res);
        isOpen.value = false;
      })
      .catch((err: any) => {
        ErrorUtils.handleError(err)
      })
      .finally(() => {
        isLoading.value = false;
      })
};
function open (sId: string | number) {
  if (!sId) {
    return ErrorUtils.handleError(new Error("id is required"));
  }
  id.value = sId;
  getEntry(props.url, sId )
      .then((res: StrapiResponse<any>) => {
       props.config.forEach((itemConfig: FormConfig) => {
          form.value[itemConfig.field] = res.data[itemConfig.field];
        })
        isOpen.value = true;
      })
      .catch((err) => {
        ErrorUtils.handleError(err)
      })
}
defineExpose({
  open
});
</script>

<template>
  <el-dialog
      v-model="isOpen"
      :title="props.title"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <!-- 将过滤后的 props 传递给 CrudForm 组件 -->
    <crud-form
        v-model="form"
        :config="props.config"
        :hide-button="true"
        ref="crudForm"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isOpen = false">取消</el-button>
        <el-button @click="save" type="primary" :loading="isLoading">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
